/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.extend.aspect;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import cn.star.framework.extend.annotation.DynamicTransactional;
import cn.star.framework.extend.core.Database;
import cn.star.framework.extend.entity.EntityWrapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DynamicTransactionalAspect {

  @Pointcut("@annotation(dynamicTransactional)")
  public void dynamicTransactionalPointcut(DynamicTransactional dynamicTransactional) {}

  @Around("dynamicTransactionalPointcut(dynamicTransactional)")
  public Object dynamicTransactional(
      ProceedingJoinPoint point, DynamicTransactional dynamicTransactional) throws Throwable {
    EntityWrapper wrapper = this.parse(point);

    try (Session session = wrapper.getSession()) {
      if (dynamicTransactional.enabled()) {
        Transaction transaction = session.beginTransaction();
        try {
          Object result = point.proceed();
          transaction.commit();
          return result;
        } catch (Throwable ex) {
          transaction.rollback();
          throw ex;
        }
      } else {
        return point.proceed();
      }
    }
  }

  private EntityWrapper parse(ProceedingJoinPoint point) {
    EntityWrapper wrapper = null;

    Object[] args = point.getArgs();

    if (ArrayUtil.isNotEmpty(args)) {
      for (Object arg : args) {
        if (arg instanceof EntityWrapper) {
          wrapper = (EntityWrapper) arg;
        }
      }
    }

    String m = point.getSignature().getName();
    String d = Database.class.getName();
    String w = EntityWrapper.class.getName();

    Assert.isFalse(
        wrapper == null, "There are no args of type {} in the args of execution method {}", w, m);

    // 需要判断 EntityWrapper 中是否存在 Database 对象，没有则认为是非法的对象

    Assert.isFalse(
        wrapper.getDatabase() == null, "There is no {} object instance in {}, illegal {}", d, w, w);

    return wrapper;
  }
}
